package cn.arikeky.system.service.impl;

import cn.arikeky.basic.query.BaseQuery;
import cn.arikeky.basic.util.PageList;
import cn.arikeky.system.domain.Role;
import cn.arikeky.system.mapper.MenuMapper;
import cn.arikeky.system.mapper.PermissionMapper;
import cn.arikeky.system.service.IRoleService;
import cn.arikeky.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author arikeky
 * @since 2022-10-24
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public PageList<Role> queryByPage(BaseQuery query) {
        PageList<Role> rolePage = super.queryByPage(query);
        List<Role> roleList = rolePage.getRows();
        List<Long> roleIds = roleList.stream().map(Role::getId).collect(Collectors.toList());
//        // 根据角色id查询 权限
//        permissionMapper.findPByRoleId(roleIds);
//        // 根据角色id查询 菜单
//        menuMapper.findMByRoleId(roleIds);
        return rolePage;
    }

    /**
     * 添加
     * @param role
     */
    @Override
    @Transactional
    public void add(Role role) {
        super.add(role);
        // 添加菜单权限
        permissionMapper.addMiddle(role.getId(),role.getPermissions());
        // 添加按钮权限
        menuMapper.addMiddle(role.getId(),role.getMenus());
    }

    /**
     * 修改
     * @param role
     */
    @Override
    @Transactional
    public void update(Role role) {
        // 修改角色表
        super.update(role);
        // 删除菜单中间表
        permissionMapper.deleteMiddle(role.getId());
        // 删除按钮中间表
        menuMapper.deleteMiddle(role.getId());
        // 添加菜单权限
        permissionMapper.addMiddle(role.getId(),role.getPermissions());
        // 添加按钮权限
        menuMapper.addMiddle(role.getId(),role.getMenus());
    }
}
